import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/complaint.dart';
import '../services/database_service.dart';
import '../services/auth_service.dart';
import '../widgets/image_viewer.dart';
import '../widgets/video_player_widget.dart';

class AdminDashboardPage extends StatefulWidget {
  const AdminDashboardPage({super.key});

  @override
  State<AdminDashboardPage> createState() => _AdminDashboardPageState();
}

class _AdminDashboardPageState extends State<AdminDashboardPage> {
  final _handleController = TextEditingController();
  final AuthService _authService = Get.find<AuthService>();
  List<Complaint> _complaints = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadComplaints();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _loadComplaints() async {
    setState(() {
      _isLoading = true;
    });
    final db = DatabaseService();
    final complaints = await db.getAllComplaints();
    setState(() {
      _complaints = complaints;
      _isLoading = false;
    });
  }

  Future<void> _processComplaint(Complaint complaint) async {
    final response = await Get.dialog<String>(
      AlertDialog(
        title: const Text('处理投诉'),
        content: TextField(
          controller: _handleController,
          decoration: const InputDecoration(
            labelText: '处理结果',
            hintText: '请输入处理结果...',
          ),
          maxLines: 3,
          onSubmitted: (value) => Get.back(result: value),
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('取消')),
          TextButton(
            onPressed: () {
              Get.back(result: _handleController.text);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (response != null && response.isNotEmpty) {
      final db = DatabaseService();
      await db.processComplaint(complaint.id!, response);
      _loadComplaints();
    }
  }

  void _showImage(BuildContext context, String imagePath) {
    Get.to(() => ImageViewer(imagePath: imagePath));
  }

  void _playVideo(BuildContext context, String videoPath) {
    Get.to(() => VideoPlayerWidget(videoPath: videoPath));
  }

  Future<void> _makePhoneCall(String phoneNumber) async {
    final status = await Permission.phone.request();
    if (status.isGranted) {
      final Uri phoneUri = Uri(scheme: 'tel', path: phoneNumber);
      if (await canLaunchUrl(phoneUri)) {
        await launchUrl(phoneUri);
      } else {
        Get.snackbar('错误', '无法拨打电话');
      }
    } else {
      Get.snackbar('需要权限', '请授予电话权限');
    }
  }

  void _logout() {
    _authService.logout();
    Get.offAllNamed('/');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('管理员控制台'),
        leading: IconButton(icon: const Icon(Icons.logout), onPressed: _logout),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadComplaints,
          ),
        ],
      ),
      body:
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : ListView.builder(
                padding: const EdgeInsets.all(16),
                itemCount: _complaints.length,
                itemBuilder: (context, index) {
                  final complaint = _complaints[index];
                  return Card(
                    margin: const EdgeInsets.only(bottom: 16),
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Chip(
                                label: Text(
                                  complaint.type == ComplaintType.air
                                      ? '大气污染'
                                      : complaint.type == ComplaintType.water
                                      ? '水污染'
                                      : '土壤污染',
                                ),
                                backgroundColor: Theme.of(
                                  context,
                                ).primaryColor.withOpacity(0.1),
                              ),
                              Text(
                                DateFormat(
                                  'yyyy-MM-dd HH:mm',
                                ).format(complaint.createdAt),
                                style: Theme.of(context).textTheme.bodySmall,
                              ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          const Text(
                            '投诉人信息',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          ListTile(
                            leading: const Icon(Icons.phone),
                            title: const Text('联系电话'),
                            subtitle: Text(complaint.phone),
                            onTap: () => _makePhoneCall(complaint.phone),
                          ),
                          const Divider(),
                          const Text(
                            '问题描述',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Text(complaint.description),
                          const SizedBox(height: 16),
                          const Text(
                            '位置信息',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 8),
                          ListTile(
                            leading: const Icon(Icons.location_on),
                            title: const Text('地址'),
                            subtitle: Text(complaint.address),
                          ),
                          const SizedBox(height: 8),
                          Text(
                            '纬度：${complaint.latitude} 经度：${complaint.longitude}',
                          ),
                          if (complaint.imagePath != null) ...[
                            const SizedBox(height: 16),
                            const Text(
                              '现场照片',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            GestureDetector(
                              onTap:
                                  () =>
                                      _showImage(context, complaint.imagePath!),
                              child: Container(
                                height: 200,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  image: DecorationImage(
                                    image: FileImage(
                                      File(complaint.imagePath!),
                                    ),
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ),
                          ],
                          if (complaint.videoPath != null) ...[
                            const SizedBox(height: 16),
                            const Text(
                              '现场视频',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            GestureDetector(
                              onTap:
                                  () =>
                                      _playVideo(context, complaint.videoPath!),
                              child: Container(
                                height: 200,
                                decoration: BoxDecoration(
                                  color: Colors.black,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: const Center(
                                  child: Icon(
                                    Icons.play_circle_filled,
                                    color: Colors.white,
                                    size: 48,
                                  ),
                                ),
                              ),
                            ),
                          ],
                          if (complaint.isProcessed &&
                              complaint.adminResponse != null) ...[
                            const SizedBox(height: 16),
                            const Text(
                              '处理结果',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Container(
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: Colors.green.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Text(
                                complaint.adminResponse!,
                                style: const TextStyle(color: Colors.green),
                              ),
                            ),
                          ],
                          if (!complaint.isProcessed) ...[
                            const SizedBox(height: 16),
                            SizedBox(
                              width: double.infinity,
                              child: ElevatedButton(
                                onPressed: () => _processComplaint(complaint),
                                child: const Text('处理投诉'),
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  );
                },
              ),
    );
  }
}
